package com.ljw.security.springmvc.controller;

import com.ljw.security.springmvc.model.AuthenticationRequest;
import com.ljw.security.springmvc.model.UserDto;
import com.ljw.security.springmvc.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @FileName LoginController
 * @Description TODO
 * @Author ljw
 * @Date 2020/8/31 13:48
 * @Version 1.0
 */
@RestController
public class LoginController {
    @Autowired
    private AuthenticationService authenticationService;

    /**
     * 用户登录------用户认证（基于session）
     *      , produces = "application/json; charset=utf-8":防止传到前台的汉字乱码
     * @param authenticationRequest 登录请求
     * @return
     */
    @PostMapping(value = "/login", produces = "application/json; charset=utf-8")
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
        System.out.println(authenticationRequest.getUsername() + "====" + authenticationRequest.getPassword());
        UserDto userDto = authenticationService.authentication(authenticationRequest);
        //用户信息存入session
        session.setAttribute(UserDto.SESSION_USER_KEY, userDto);
        return userDto.getFullname() + " 登录成功";
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @GetMapping(value = "logout", produces = "application/json; charset=utf-8")
    public String logout(HttpSession session) {
        //登出时将session置为 失效。
        session.invalidate();
        return "退出成功";
    }

    /**
     * 测试资源1----用户鉴权(基于session+拦截器)
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r1", produces = "application/json; charset=utf-8")
    public String r1(HttpSession session) {
        String fullname = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userObj != null) {
            fullname = ((UserDto) userObj).getFullname();
        } else {
            fullname = "匿名";
        }
        return fullname + " 访问资源1";
    }

    /**
     * 测试资源2----用户鉴权(基于session)
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r2", produces = "application/json; charset=utf-8")
    public String r2(HttpSession session) {
        String fullname = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userObj != null) {
            fullname = ((UserDto) userObj).getFullname();
        } else {
            fullname = "匿名";
        }
        return fullname + " 访问资源2";
    }


}
